package com.saascloud.datasource.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.saascloud.datasource.core.TenantDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * @Author: liangxu
 * @Contact: one_dream@aliyun.com
 * @Date: 2022/5/17 15:21
 * @Version: 1.0
 * @Description:企服saas化多数据源支持，从默认数据库的tenant_config加载数据库配置用于租户数据源切：select tenant_id, config_content from tenant_config where config_item='db'
 * 默认数据源使用以下配置加载
 * 在执行之前需要调用TenantContext.setTenantId设置租户id信息，使用完后及时清理
 */
@Slf4j
@ConditionalOnProperty(name = "saas.enable.datasource", havingValue = "true")
@AutoConfigureBefore({DruidDataSourceAutoConfigure.class, DataSourceAutoConfiguration.class})
public class TenantDataSourceAutoConfiguration {
    /**
     * 数据源
     *
     * @return
     */
    @Bean
    public TenantDataSource dynamicDataSource(Environment environment) {
        log.info("初始化租户多数据源插件");
        return new TenantDataSource(environment);
    }

}
